﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.Metadata.EntityElement;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PMAF.K3Cloud.SCM.DynamicForm.BusinessPlugIn
{
    [HotUpdate]
    [Description("采购流水号校对")]
    public class PurchaseSnCheck : AbstractDynamicFormPlugIn
    {
        public override void BarItemClick(BarItemClickEventArgs e)
        {
            base.BarItemClick(e);
            switch (e.BarItemKey.ToUpperInvariant())
            {
                case "PMAF_CHECKBTN":
                    
                    ////构建采购流水号范围数据
                    //Entity entity = View.BillBusinessInfo.GetEntity("F_PMAF_PurSnEntry");
                    ////转换成行
                    //DynamicObjectCollection rows = View.Model.GetEntityDataObject(entity);
                    //int[] purchaseIds = new int[rows.Count];
                    //int index = 0;
                    //foreach(DynamicObject row in rows)
                    //{
                    //    int purchaseId = Convert.ToInt32(row["F_PMAF_PurchaseSn_Id"]);
                    //    purchaseIds[index] = purchaseId;
                    //    index++;
                    //}
                    //string purchaseStr = GetPurchaseIds(purchaseIds);
                    ////流水号采销状况
                    //string sqlStr1 = string.Format(@"/*dialect*/SELECT
                    //e0.F_PMAF_PURCHASESN,
                    //e0.FQTY AS PURQTY,
                    //CASE
                    // WHEN e1.FQTY IS NULL THEN 0
                    // ELSE e1.FQTY
                    //END AS SALEQTY
                    //INTO #TEMP
                    //FROM T_PUR_POORDERENTRY e0
                    //FULL OUTER JOIN(
                    //SELECT
                    //t1.F_PMAF_PURCHASESN,
                    //t2.FNUMBER,
                    //SUM(t1.FQTY) AS FQTY
                    //FROM T_SAL_ORDERENTRY t1
                    //LEFT JOIN PMAF_t_PurchaseSn t2 ON t1.F_PMAF_PURCHASESN=t2.FID
                    //WHERE t1.F_PMAF_PURCHASESN<>0
                    //GROUP BY t1.F_PMAF_PURCHASESN,t2.FNUMBER) e1 ON e1.FNUMBER=e0.F_PMAF_PURCHASESN;
                    //SELECT
                    //d1.FID,
                    //d0.F_PMAF_PURCHASESN,
                    //d0.PURQTY,
                    //d0.SALEQTY,
                    //d0.PURQTY-d0.SALEQTY AS REMAINQTY,
                    //d1.F_PMAF_PURQTY,
                    //d1.F_PMAF_CURRENTQTY
                    //INTO #TEMP2
                    //FROM #TEMP d0
                    //LEFT JOIN PMAF_t_PurchaseSn d1 ON d1.FNUMBER=d0.F_PMAF_PURCHASESN
                    //WHERE PURQTY<>F_PMAF_PURQTY{0};
                    //UPDATE PMAF_t_PurchaseSn SET F_PMAF_PURQTY=t1.PURQTY
                    //FROM PMAF_t_PurchaseSn t0
                    //JOIN #TEMP2 t1
                    //ON t0.FID=t1.FID;
                    //DROP TABLE #TEMP2;
                    //", purchaseStr);
                    ////检查采购订单数量与流水号采购数量
                    //string sqlStr2 = string.Format(@"/*dialect*/
                    //SELECT
                    //d1.FID,
                    //d0.F_PMAF_PURCHASESN,
                    //d0.PURQTY,
                    //d0.SALEQTY,
                    //d0.PURQTY-d0.SALEQTY AS REMAINQTY,
                    //d1.F_PMAF_PURQTY,
                    //d1.F_PMAF_CURRENTQTY
                    //INTO #TEMP2
                    //FROM #TEMP d0
                    //LEFT JOIN PMAF_t_PurchaseSn d1 ON d1.FNUMBER=d0.F_PMAF_PURCHASESN
                    //WHERE PURQTY<>F_PMAF_PURQTY{0};
                    //", purchaseStr);
                    ////更新采购流水号采购数量
                    //string sqlStr3 = string.Format(@"/*dialect*/
                    //UPDATE PMAF_t_PurchaseSn SET F_PMAF_PURQTY=t1.PURQTY
                    //FROM PMAF_t_PurchaseSn t0
                    //JOIN #TEMP2 t1
                    //ON t0.FID=t1.FID;
                    //");
                    ////删除临时表
                    //string sqlStr4 = string.Format(@"/*dialect*/
                    //DROP TABLE #TEMP2;
                    //");
                    ////检查采销结余数量与流水号当前数量
                    //string sqlStr5 = string.Format(@"SELECT
                    //d1.FID,
                    //d0.F_PMAF_PURCHASESN,
                    //d0.PURQTY,
                    //d0.SALEQTY,
                    //d0.PURQTY-d0.SALEQTY AS REMAINQTY,
                    //d1.F_PMAF_PURQTY,
                    //d1.F_PMAF_CURRENTQTY
                    //INTO #TEMP2
                    //FROM #TEMP d0
                    //LEFT JOIN PMAF_t_PurchaseSn d1 ON d1.FNUMBER=d0.F_PMAF_PURCHASESN
                    //WHERE (d0.PURQTY-d0.SALEQTY)<>F_PMAF_CURRENTQTY{0};
                    //", purchaseStr);
                    ////更新流水号当前数量
                    //string sqlStr6 = string.Format(@"/*dialect*/
                    //UPDATE PMAF_t_PurchaseSn SET F_PMAF_CURRENTQTY=t1.REMAINQTY
                    //FROM PMAF_t_PurchaseSn t0
                    //JOIN #TEMP2 t1
                    //ON t0.FID=t1.FID;
                    //");
                    ////删除临时表
                    //string sqlStr7 = string.Format(@"/*dialect*/
                    //DROP TABLE #TEMP;
                    //DROP TABLE #TEMP2;
                    //");
                    //string sql1 = string.Concat(sqlStr1, sqlStr2);
                    //采购订单数量与流水号采购数量存在差异的数据
                    //DynamicObjectCollection dt1 = DBUtils.ExecuteDynamicObject(Context, string.Concat(sqlStr1,sqlStr2));
                    //执行更新结果
                    //int dt1Result = DBUtils.Execute(Context, sqlStr1);
                    //int delTemp2 = DBUtils.Execute(Context, sqlStr4);
                    //采销结余数量与流水号当前数量存在差异的数据
                    //DynamicObjectCollection dt2 = DBUtils.ExecuteDynamicObject(Context, string.Concat(sqlStr1, sqlStr5));
                    //执行更新结果
                    //int dt2Result = DBUtils.Execute(Context, sqlStr6);
                    //int delTemp = DBUtils.Execute(Context, sqlStr7);
                    break;
                case "PMAF_UPDATE": //更新销售出库单采购流水号子单据体

                    //查询采购流水号子单据体数据
                    string purchaseSnStr = string.Format(@"/*dialect*/SELECT
                    FENTRYID,
                    FDetailID,
                    FSEQ,
                    F_PMAF_SALEQTY,
                    F_PMAF_DETAILPURCHASEPRICE,
                    F_PMAF_DETAILPURCHASESN FROM PMAF_t_OUTSTOCKPURCHASESN");

                    DynamicObjectCollection purchaseSnEntries = DBUtils.ExecuteDynamicObject(Context, purchaseSnStr);

                    //获取子单据体中明细单据体的ID集
                    int[] purchaseSnEntryIds = new int[purchaseSnEntries.Count];
                    int purchaseSnEntryIndex = 0;
                    int maxId = 0;
                    foreach (var entry in purchaseSnEntries)
                    {
                        purchaseSnEntryIds[purchaseSnEntryIndex] = Convert.ToInt32(entry["FENTRYID"]);
                        int detailId = Convert.ToInt32(entry["FDETAILID"]);
                        if (detailId > maxId)
                        {
                            maxId = detailId;
                        }
                        purchaseSnEntryIndex++;
                    }
                    //获取过滤字符串
                    string purchaseSnFilter = GetEntryIds(purchaseSnEntryIds);
                    //查询到需要更新的明细数据
                    string entryStr = string.Format(@"/*dialect*/SELECT
                    FENTRYID,
                    FREALQTY,
                    F_PMAF_PURPRICE,
                    F_PMAF_PURCHASESN
                    FROM T_SAL_OUTSTOCKENTRY
                    WHERE FENTRYID NOT IN {0}", purchaseSnFilter);
                    DynamicObjectCollection outStockEntries = DBUtils.ExecuteDynamicObject(Context, entryStr);

                    //逐行向流水号子单据体添加数据
                    int success = 0;
                    foreach (var entry in outStockEntries)
                    {
                        maxId++;
                        int entryId = Convert.ToInt32(entry["FENTRYID"]);
                        string insertStr = string.Format(@"/*dialect*/INSERT INTO
                        PMAF_t_OUTSTOCKPURCHASESN (FENTRYID,FDETAILID,FSEQ,F_PMAF_SALEQTY,F_PMAF_DETAILPURCHASEPRICE,F_PMAF_DETAILPURCHASESN)
                        SELECT FENTRYID,{0},1,FREALQTY,F_PMAF_PURPRICE,F_PMAF_PURCHASESN
                        FROM T_SAL_OUTSTOCKENTRY
                        WHERE FENTRYID = {1}", maxId, entryId);
                        success += DBUtils.Execute(Context, insertStr);
                    }

                    View.ShowMessage($"success executed {success} records!");
                    break;
                default:
                    break;
            }
        }

        private string GetPurchaseIds(int[] ids)
        {
            StringBuilder sb = new StringBuilder();
            if (ids.Length > 0)
            {
                sb.Append(" AND d1.FID IN (");
                int i = 0;
                foreach (var item in ids)
                {
                    sb.Append(item);
                    if (i < ids.Length - 1)
                    {
                        sb.Append(",");
                    }
                    i++;
                }
                sb.Append(")");
            }
            return sb.ToString();
        }

        private string GetEntryIds(int[] ids)
        {
            StringBuilder sb = new StringBuilder();
            if (ids.Length > 0)
            {
                sb.Append("(");
                int i = 0;
                foreach (var item in ids)
                {
                    sb.Append(item);
                    if (i < ids.Length - 1)
                    {
                        sb.Append(",");
                    }
                    i++;
                }
                sb.Append(")");
            }
            return sb.ToString();
        }
    }
}
